#!/bin/bash
source tools/getenv.sh

validCurrDirIsLink


function mySupervisorRestart() {
    echo ""
}
function mySystemdRestart() {
    echo ""
}

# 目前都是一样的，发送一个HUP信号
function myRestart() {
  echo -e "$BOLD_WHITE 判断服务进程是否存在...$RESET"

  psServerBinAllPath
  num=$(getServerBinAllPathNum)
  if [[ $num -eq 0 ]]; then
    echo -e "${GREEN}进程不存在，启动程序...$RESET"
    startStock
  else
    echo -e "${GREEN}进程存在$RESET"
    echo -e "=========================== $GREEN 进程存在,重启$RESET ==========================="
    oldPid=$(getPidFromPidFile)
    echo -e "$RED 旧进程id： $oldPid $RESET"
    echo  -e "$GREEN 开始重启...$RESET"
    kill -HUP "$oldPid"
    echo -e "$GREEN 重启完成$RESET"
    psServerBinAllPath
    echo -e "$GREEN 睡2秒... $RESET"
    echo -e "$GREEN --------------------------------------- 重启之后 --------------------------------- $RESET"
    sleep 2
    newPid=$(getPidFromPidFile)
    echo -e "$GREEN  新进程id： $newPid $RESET"
    if [[ "$oldPid" -eq "$newPid" ]]; then
      echo -e "$RED 重启失败，进程id没有变化$RESET"
    else
      echo -e "$BOLD_WHITE 重启成功,进程id: $RED $oldPid --${GREEN}-> $newPid $RESET"
      # shellcheck disable=SC2009
      psServerBinAllPath
    fi
  fi
}

function myDevRestart() {
  echo -e "$BOLD_WHITE 判断进程是否存在...$RESET"
  # shellcheck disable=SC2046
  # shellcheck disable=SC2006
  # shellcheck disable=SC2126
  # shellcheck disable=SC2009
  num=$(getGrepPidFileNum)
  if [[ $num -eq 0 ]]; then
    echo -e "${GREEN}进程不存在，启动程序...$RESET"
    nohup ./stock &
  else
    echo -e "${GREEN}进程存在$RESET"
    echo -e "=========================== $GREEN 进程存在,重启$RESET ==========================="
    oldPid=$(getPidFromPidFile)
    echo -e "$RED 旧进程id： $oldPid $RESET"
    echo  -e "$GREEN 开始重启...$RESET"
    kill -HUP "$oldPid"
    echo -e "$GREEN 重启完成$RESET"
    # shellcheck disable=SC2009
    psServerBinAllPath
    echo -e "$GREEN 睡2秒... $RESET"
    sleep 2
    newPid=$(getPidFromPidFile)
    echo -e "$GREEN  新进程id： $newPid $RESET"
    if [[ "$oldPid" -eq "$newPid" ]]; then
      echo -e "$RED 重启失败，进程id没有变化$RESET"
    else
      echo -e "$BOLD_WHITE 重启成功,进程id: $RED $oldPid --${GREEN}-> $newPid $RESET"
    fi
    # shellcheck disable=SC2009
    psServerBinAllPath
  fi
}

if [[ "$env" == "dev" ]]; then
  myDevRestart
elif [[ "$env" == "test" || "$env" == "prod" ]]; then
  myRestart
fi
